/*
 * Copyright (c) 2011  Cristian Constantin
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package com.quizio.engine.player;

import com.quizio.engine.dao.QuizSessionDao;
import com.quizio.engine.enums.QuizSessionState;
import com.quizio.engine.model.Question;
import com.quizio.engine.model.QuestionUserInput;
import com.quizio.engine.model.QuizSession;
import com.quizio.engine.session.QuizSessionService;
import com.quizio.engine.validator.QuizValidationService;
import com.quizio.security.SecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Support class for the user's interaction with the internal
 * quiz engine.
 *
 * @author Cristian Constantin
 * @since 10/16/11
 */
@Service
@Transactional
public class QuizPlayerService {

    @Autowired
    private QuizSessionDao sessionDao;

    @Autowired
    private SecurityManager securityManager;

    @Autowired
    private QuizSessionService quizSessionService;

    @Autowired
    private QuizValidationService validationService;

    /**
     * The accepted extra time when evaluating the quiz time limit, in seconds.
     */
    private static final long ACCEPTED_TIME_LIMIT_ERROR = 10;

    /**
     * Retrieves the active quiz session of the current logged on user.
     *
     * @return the active quiz session, if any
     */
    public QuizSession getUserActiveSession() {
        return sessionDao.getUserActiveSession(securityManager.getCurrentAuthenticatedUser());
    }

    /**
     * Returns the next question and updates the active question index
     * on the specified session.
     *
     * @param session the quiz session
     * @return the next question or <code>null</code> if we reached the end of the test
     */
    public Question getNextQuestion(QuizSession session) {

        Question question;

        if (session.getCurrentQuestion() < session.getQuiz().getQuestions().size()) {
            session.setCurrentQuestion(session.getCurrentQuestion() + 1);
            question = session.getQuiz().getQuestions().get(session.getCurrentQuestion());
        } else {
            throw new RuntimeException("This was the last question");
        }

        sessionDao.update(session);

        return question;
    }


    /**
     * Updates the active question index of the specified session.
     *
     * @param session the quiz session
     * @param index   the index of the current question
     */
    public void setCurrentQuestion(QuizSession session, int index) {

        if (0 < index && index <= session.getQuiz().getQuestions().size()) {
            session.setCurrentQuestion(index);
        } else {
            throw new RuntimeException("Invalid question index");
        }

        sessionDao.update(session);
    }


    /**
     * Returns the current quiz question.
     *
     * @param session the quiz session
     * @return the current question
     */
    public QuestionUserInput getCurrentQuestion(QuizSession session) {

        return session.getQuestionsInputs().get(session.getCurrentQuestion() - 1);
    }


    /**
     * Records the user's answer for the specified question.
     *
     * @param session the active quiz session
     * @param answer  the actual answer
     */
    public void submitAnswer(QuizSession session, String answer) {

        //checkTimeLimit(session); disable for now

        QuestionUserInput question = session.getQuestionsInputs().get(session.getCurrentQuestion() - 1);
        question.setAnswer(answer);
    }

    /**
     * Checks whether an answer submission is done in the specified quiz time limit.
     * <p/>
     * If the answer submission is not within the session's time limit an exception
     * is thrown and the user's answer is not recorded.
     *
     * @param session the active quiz session
     */
    private void checkTimeLimit(QuizSession session) {

        if (session.getQuiz().getMaxDuration() > 0) {

            long timeElapsed = (System.currentTimeMillis() - session.getStartTime().getTime()) / 1000;

            assert (session.getQuiz().getMaxDuration() + ACCEPTED_TIME_LIMIT_ERROR >= timeElapsed);
        }
    }

    /**
     * Closes the quiz session and sends the recorded user input to server-side validation.
     * Further input from the user will not be possible.
     *
     * @param session the quiz session to submit
     */
    public void submitQuiz(QuizSession session) {
        session.setActive(false);
        session.setClosed(true);
        session.setEndTime(new Date());
        session.setState(QuizSessionState.FINISHED);
        validationService.validateQuiz(session);

        sessionDao.update(session);
    }
}
